package com.zone.vehicle.superApps.view.common;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.zone.vehicle.superApps.view.common.listener.ActionEnum;
import com.zone.vehicle.superApps.view.common.listener.ActionListener;
import com.zone.vehicle.superApps.view.setting.widget.CustomDialog;

import org.apache.commons.lang3.ObjectUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

public abstract class HandledFragment extends Fragment implements IFragment {

    private static final String TAG = HandledFragment.class.getSimpleName();

    protected static List<ActionListener> listeners = new ArrayList<>();

    private static LinkedList<String> pageList = new LinkedList<>();

    private static LinkedHashMap<String, String> pageMap = new LinkedHashMap<>();

    private static Context context;

    public void addListener(ActionListener listener) {
        listeners.add(listener);
    }

    public void removeListener(ActionListener listener) {
        listeners.remove(listener);
    }

    public boolean onAction(ActionEnum action) {
        if (ObjectUtils.isNotEmpty(listeners)) {
            for (ActionListener listener : listeners) {
                if (listener.onAction(action)) {
                    return true;
                }
            }
        }
        return false;
    }


    public boolean changePage(String pageName) {
        if (change(pageName)) {
            String lastPage = getClass().getSimpleName();
            pageList.add(lastPage);
            return true;
        }
        return false;
    }

    public boolean onBack() {
        if (ObjectUtils.isNotEmpty(pageList)) {
            return change(pageList.removeLast());
        } else {
            requireActivity().finish();
        }
        return false;
    }

    private boolean change(String pageName) {
        if (ObjectUtils.isNotEmpty(listeners)) {
            for (ActionListener listener : listeners) {
                if (listener.onPageChanged(pageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void initFragmentPages() {

    }

    @Override
    public void onCreate(@org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = requireContext();
    }

    public boolean onBackClicked(Fragment fragment) {
        return BackHandlerHelper.handleBackPress(fragment);
    }

    public void showToast(String txt) {
        Toast.makeText(
                requireActivity().getApplicationContext(),
                txt,
                Toast.LENGTH_LONG).show();
    }

    public void showDialog(){
        CustomDialog dialog = new CustomDialog(context);
        dialog.setTitle("标题");
        dialog.setSubTitle("副标题");
        dialog.setPositive("是");
        dialog.setNegtive("否");
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.cancel();
            }
        });
        dialog.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                Toast.makeText(context, "开始下载安装", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNegtiveClick() {
                dialog.cancel();
            }
        });
        dialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
//        initIDigitalZoneStoreService();
    }

    @Override
    public void onPause() {
        super.onPause();
        // TODO 系统接口需要依赖车机环境，正式环境放开
//        stopOfferService();
    }

    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.equals(action, "download")){
                String data = intent.getStringExtra("data");

            }
        }
    }

    /************************************ICM**************************************************/
//
//    static Handler handler = new Handler(new Handler.Callback() {
//        @Override
//        public boolean handleMessage(@NonNull Message msg) {
//
//            Log.d(TAG, msg.toString());
//            switch (msg.what){
//                case 1:
//                    AppInfoStruct appInfoStruct = (AppInfoStruct)msg.obj;
//                    downLoad(appInfoStruct);
//                    break;
//            }
//            return false;
//        }
//    });
//
//
//    private static void downLoad(AppInfoStruct appInfoStruct){
//        File dir = new File(context.getCacheDir(), "download");
//        if (!dir.exists()){
//            dir.mkdirs();
//        }
//        File saveFile = new File(dir, appInfoStruct.getAppID()+".apk");
//        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appInfoStruct.getAppID());
//        if (ObjectUtils.isNotEmpty(download)){
//            DownloadDaoUtilsStore.getInstance().deleteByCode(download.getCode());
//            download = null;
//        }
//        if (ObjectUtils.isEmpty(download)){
//            download = new Download();
//            download.setCode(appInfoStruct.getAppID());
//            download.setDownloadStatus(DownloadStatus.PREPARE_DOWNLOAD);
//            download.setDownloadUrl(appInfoStruct.getDownloadURL());
//            download.setFilePath(saveFile.getPath());
//            download.setDownloadLocation(0);
//            download.setType("1");
//            download.setVersion("");
//            download.setCreateTime(new Date().toString());
//            DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().insert(download);
//            DownloadHelper.getInstance().addTask(appInfoStruct.getAppID(), saveFile, download.getDownloadStatus(), 0, "0", appInfoStruct.getVehicleVIN()).submit(context);
//        } else {
//            if (download.getDownloadStatus() == DownloadStatus.PAUSE_DOWNLOAD
//                    || download.getDownloadStatus() == DownloadStatus.FAIL_DOWNLOAD){
////                    download.setDownloadStatus(DownloadStatus.PAUSE_DOWNLOAD);
//                DownloadHelper.getInstance().addTask(appInfoStruct.getAppID(), saveFile, DownloadStatus.PREPARE_DOWNLOAD, 0, "0", appInfoStruct.getVehicleVIN()).submit(context);
//            }
//        }
//    }
//// TODO 系统接口需要依赖车机环境，正式环境放开
//
//    private MyIDigitalZoneStoreService storeService;
//    private DigitalZoneStoreServiceStub serviceStub;
//
//
//
//    // TODO 系统接口需要依赖车机环境，正式环境放开
//    protected void initIDigitalZoneStoreService() {
//        Log.d(TAG, "initIDigitalZoneStoreService");
//        storeService = new MyIDigitalZoneStoreService();
//        serviceStub = new DigitalZoneStoreServiceStub(storeService, DigitalZoneStoreServiceStub.INSTANCE_NAME_1, "/vendor/etc/sovp/com.zone.soa.digitalzonestoreskeleton");
//        serviceStub.offerService();
//    }
//
//    protected void stopOfferService() {
//        if (serviceStub != null){
//            Log.d(TAG, "stopOfferService");
//            serviceStub.stopOfferService();
//        }
//    }
//
//    // TODO 系统接口需要依赖车机环境，正式环境放开
//    static class MyIDigitalZoneStoreService implements IDigitalZoneStoreService {
//
//        @Override
//        public APPContinueInfoOutput aPPContinueInfo(AppInfoStruct appInfoStruct) {
//            Log.d(TAG, "aPPContinueInfo="+ JSON.toJSONString(appInfoStruct));
//            APPContinueInfoOutput output = new APPContinueInfoOutput();
//            if (ObjectUtils.isNotEmpty(appInfoStruct)){
//                output.respCode = "SUCCESS";
//
//            }else {
//                output.respCode = "FAILED";
//
//            }
//            return output;
//        }
//
//        @Override
//        public AppDownloadInfoOutput appDownloadInfo(AppInfoStruct appInfoStruct) {
//            Log.d(TAG, "appDownloadInfo===="+ JSON.toJSONString(appInfoStruct));
//            Message message = new Message();
//            message.what = 1;
//            message.obj = appInfoStruct;
//            handler.sendMessage(message);
////            CustomDialog dialog = new CustomDialog(context);
////            dialog.setTitle(appInfoStruct.getConsumerName());
////            dialog.setSubTitle("");
////            dialog.setPositive("同意");
////            dialog.setNegtive("不同意");
////            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
////                @Override
////                public void onCancel(DialogInterface dialog) {
////                    dialog.cancel();
////                }
////            });
////            dialog.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
////                @Override
////                public void onPositiveClick() {
////                    Message message = new Message();
////                    message.what = 1;
////                    message.obj = appInfoStruct;
////                    handler.sendMessage(message);
////                    Toast.makeText(context, "开始下载安装", Toast.LENGTH_SHORT).show();
//////                    DownloadHelper.getInstance().addTask(appInfoStruct.getAppID(), null, DownloadStatus.PREPARE_DOWNLOAD, 0, "").submit(context);
////                }
////
////                @Override
////                public void onNegtiveClick() {
////                    dialog.cancel();
////                }
////            });
////            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
////            dialog.show();
//
//            AppDownloadInfoOutput output = new AppDownloadInfoOutput();
//            output.respCode = "SUCCESS";
//            return output;
//        }
//
//        @Override
//        public AppPauseInfoOutput appPauseInfo(AppInfoStruct appInfoStruct) {
//            Log.d(TAG, "appPauseInfo="+ JSON.toJSONString(appInfoStruct));
//            AppPauseInfoOutput output = new AppPauseInfoOutput();
//            output.respCode = "SUCCESS";
//            return output;
//        }
//
//        @Override
//        public AppUninstallInfoOutput appUninstallInfo(AppInfoStruct appInfoStruct) {
//            Log.d(TAG, "appUninstallInfo="+ JSON.toJSONString(appInfoStruct));
//            AppUninstallInfoOutput output = new AppUninstallInfoOutput();
//            output.respCode = "SUCCESS";
//            return output;
//        }
//
//        @Override
//        public AppUpdateInfoOutput appUpdateInfo(AppInfoStruct appInfoStruct) {
//            Log.d(TAG, "appUpdateInfo="+ JSON.toJSONString(appInfoStruct));
//            AppUpdateInfoOutput output = new AppUpdateInfoOutput();
//            output.respCode = "SUCCESS";
//            return output;
//        }
//    }
}
